package com.kcht.np.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kcht.np.common.domain.TreeNode;
import com.kcht.np.common.exception.ParameterException;
import com.kcht.np.entity.SysDepartment;
import com.kcht.np.service.SysDepartmentService;
import com.kcht.np.util.JsonResult;
import com.kcht.np.vo.page.QueryParameter;
import com.kcht.np.util.TreeNodeUtils;
import com.kcht.np.vo.dept.DeptCanCreateInfo;
import com.kcht.np.vo.dept.DeptCanModifyInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
  * <p>
  * 部门管理 控制器
  * </p>
  *
  * @Package:        com.kcht.np.mp.controller
  * @Description:    部门管理 控制器
  * @Author:         liuqi
  * @CreateDate:     2020/3/31 11:26
 */


@Slf4j
@Api(tags = "[ 权限管理 ] 部门管理")
@SuppressWarnings("all")
@RestController
@RequestMapping("/sys/department")
public class SysDepartmentController{

    @Autowired
    protected SysDepartmentService deptService;

    /*--------------查询部门----------------------*/
    /*管理员查询*/
    @ApiOperation(value = "查询所有", notes = "查询所有部门")
    @GetMapping("/all")
    @PreAuthorize("hasAnyAuthority('pre_dept')||hasAnyAuthority('pre_user')")
    public JsonResult<List<SysDepartment>> queryDepts() {
        return JsonResult.success(deptService.list());
    }

    @ApiOperation(value = "分页", notes = "分页 查询所有")
    @GetMapping("/page")
    @PreAuthorize("hasAnyAuthority('pre_dept')||hasAnyAuthority('pre_user')")
    public JsonResult<Page<SysDepartment>> pagingQueryDepts(QueryParameter parameter,BindingResult br) {
        IPage<SysDepartment> page = new Page<SysDepartment>(parameter.getPageNum(), parameter.getPageSize());
        IPage<SysDepartment> iPage = deptService.page(page);
        return JsonResult.success(iPage.getPages(), iPage.getTotal(),iPage.getRecords());
    }
    @ApiOperation(value = "查询所有[树节点]", notes = "以树节点的形式展示")
    @GetMapping("/tree")
    @PreAuthorize("hasAnyAuthority('pre_dept')||hasAnyAuthority('pre_user')")
    public JsonResult tree() {
        List<TreeNode> collect = deptService.list()
                .stream()
                .distinct()
                .map(res -> new TreeNode(res.getId(), res.getName(), res.getParentId(), res, null))
                .collect(Collectors.toList());
        List<TreeNode> roots = TreeNodeUtils.findRoots(collect);
        return JsonResult.success(roots);
    }

    @ApiOperation(value = "创建部门", notes = "创建新部门")
    @PreAuthorize("hasAnyAuthority('pre_dept:create')")
    @PostMapping
    public JsonResult<SysDepartment> create(@RequestBody @Validated DeptCanCreateInfo info, BindingResult br) {
            try {
           deptService.createDept(info);
            return JsonResult.success();
        } catch (ParameterException e) {
            return JsonResult.result(400,e.getMessage());
        }
    }

    @ApiOperation(value = "更新部门", notes = "更新部门信息")
    @PreAuthorize("hasAnyAuthority('pre_dept:update')")
    @PutMapping
    public JsonResult<SysDepartment> update(@RequestBody @Validated DeptCanModifyInfo info, BindingResult br) {
        try {
           deptService.updateDept(info);
           return JsonResult.success();
        } catch (ParameterException e) {
            return JsonResult.result(400,e.getMessage());
        }
    }

    @ApiOperation(value = "删除部门", notes = "删除部门")
    @PreAuthorize("hasAnyAuthority('pre_dept:delete')")
    @DeleteMapping("/{id}")
    public JsonResult<String> delete(@PathVariable("id") Long id) {
        try {
            deptService.removeDeptById(id);
            return JsonResult.success();
        } catch (Exception e) {
            return JsonResult.result(400,e.getMessage());
        }
    }
}
